/*
   Copyright 2009 Abdulla Abdurakhmanov (abdulla@latestbit.com)
   Original sources are available at www.latestbit.com

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

package org.latestbit.smartobjects.core;

import static org.junit.Assert.*;

import java.net.URI;
import java.util.Calendar;

import org.junit.Test;
import org.latestbit.smartobjects.ISmartBus;
import org.latestbit.smartobjects.SmartBus;
import org.latestbit.smartobjects.coders.CallInterfaceOperationRequest;
import org.latestbit.smartobjects.coders.CallInterfaceOperationResponse;
import org.latestbit.smartobjects.network.EndpointLocation;
import org.latestbit.smartobjects.network.tcp.tests.TCPTestServer;

public class RemoteSmartObjectTest {

	@Test
	public void testRemoteSmartObjectConnect() throws Exception {
		ISmartBus bus = new SmartBus();
		final String location = "tcp://localhost:7777";

		TCPTestServer server = new TCPTestServer(new URI(location), bus.getManagedNetwork().getNetworkFactory());
		server.getAcceptor().start();
		
		DummyRemoteObject dummySmartObject = new DummyRemoteObject();
		dummySmartObject.resolve(bus, new EndpointLocation(bus, location) );
		assertTrue(dummySmartObject.isAvailable());
		
		server.getAcceptor().stop();
	}
	
	@Test
	public void testSmartObjectProcessRequest() throws Exception {
		ISmartBus bus = new SmartBus();
		final String location = "tcp://localhost:7777";
		
		DummySyncServerObject dummyServerObject = new DummySyncServerObject();				
		dummyServerObject.publish(bus, new EndpointLocation(bus, location));
		
		DummyRemoteObject dummyClientObject = new DummyRemoteObject();
		dummyClientObject.resolve(bus, new EndpointLocation(bus, location) );
		
		assertTrue(dummyClientObject.isAvailable());
		assertEquals(dummyServerObject.getInterfaceId(), dummyClientObject.getInterfaceId());

		dummyClientObject.getDefaultRequestContext().setMaxResponseTimeoutInSec(5);
		CallInterfaceOperationRequest callRequest = 
			dummyClientObject.createCallRequest("TestOperation", null);
		
		CallInterfaceOperationResponse callResponse = dummyClientObject.call(dummyClientObject.getConnectionHandlerToSend(), callRequest);
		assertEquals(callResponse.getMessageId(), callRequest.getMessageId());
		
		byte[] receivedBuffer = new byte[DummySyncServerObject.TEST_BUFFER.length];
		callResponse.getBuffer().getBuffer().get(receivedBuffer);
		assertArrayEquals(DummySyncServerObject.TEST_BUFFER, receivedBuffer);
		
		assertNull ( dummyClientObject.getLastCallResponse() );

		// Create a new request for async test
		dummyClientObject.getDefaultRequestContext().setMaxResponseTimeoutInSec(5);
		callRequest = 
			dummyClientObject.createCallRequest("TestOperation", null);
		
		dummyClientObject.getConditionLock().lock();
		dummyClientObject.callAsync(dummyClientObject.getConnectionHandlerToSend(), callRequest, null);
		dummyClientObject.waitCondition();
		dummyClientObject.getConditionLock().unlock();
		assertNotNull ( dummyClientObject.getLastCallResponse() );
		assertEquals( dummyClientObject.getLastCallResponse().getMessageId(), callRequest.getMessageId());
		receivedBuffer = new byte[DummySyncServerObject.TEST_BUFFER.length];
		dummyClientObject.getLastCallResponse().getBuffer().getBuffer().get(receivedBuffer);
		assertArrayEquals(DummySyncServerObject.TEST_BUFFER, receivedBuffer);
		
		dummyServerObject.destroy();
		dummyClientObject.destroy();
	}

	@Test
	public void testRequestProcessingPerf() throws Exception {
		
		ISmartBus bus = new SmartBus();
		final String location = "tcp://localhost:7777";
		
		DummySyncServerObject dummyServerObject = new DummySyncServerObject();				
		dummyServerObject.publish(bus, new EndpointLocation(bus, location));
		
		DummyRemoteObject dummyClientObject = new DummyRemoteObject();
		dummyClientObject.resolve(bus, new EndpointLocation(bus, location) );
		
		assertTrue(dummyClientObject.isAvailable());
		assertEquals(dummyServerObject.getInterfaceId(), dummyClientObject.getInterfaceId());
		
		dummyClientObject.getDefaultRequestContext().setMaxResponseTimeoutInSec(5);
		
		System.out.println("Run performance test for processing sync/async requests");
		CallInterfaceOperationRequest callRequest;
		long startTime, endTime, progressTime1, progressTime2, tps = 0, maxTps = 0, minTps = Long.MAX_VALUE, midTps = 0;
        final int PRF_ITER_SYNC_CNT = 40000;
        final int PRF_ITER_ASYNC_CNT = 400000;
        
        final int ALLOWED_MAX_SYNC_TPS_LWM = 1000;
        final int ALLOWED_MAX_ASYNC_TPS_LWM = 15000;
        dummyClientObject.getDefaultRequestContext().setMaxResponseTimeoutInSec(5);
        startTime = Calendar.getInstance().getTimeInMillis();        
        progressTime1 = startTime;
        progressTime2 = startTime;
		for(int i=0;i<PRF_ITER_SYNC_CNT;i++, tps++) {
			callRequest = 
				dummyClientObject.createCallRequest("TestOperation", null);
			dummyClientObject.call(dummyClientObject.getConnectionHandlerToSend(), callRequest);
			progressTime1 = Calendar.getInstance().getTimeInMillis();
			if(progressTime1 > progressTime2 + 1000) {
				// System.out.println("TPS: "+tps);
				progressTime2 = progressTime1;
				if(maxTps<tps)
					maxTps = tps;
				if(minTps>tps)
					minTps = tps;
				midTps+= tps;
				tps = 0;
			}
		}
		
        endTime = Calendar.getInstance().getTimeInMillis();
        midTps = (long) (midTps / ((endTime-startTime)/1000.0));
        System.out.println("Elapsed time for sync model: "+ ((endTime-startTime)/1000.0)+". Mid. Resp. Time: "+(endTime-startTime)/PRF_ITER_SYNC_CNT+". Max TPS: "+maxTps+". Min TPS: "+minTps+". Mid TPS: "+midTps);
        assertTrue(maxTps > ALLOWED_MAX_SYNC_TPS_LWM );
        
        startTime = Calendar.getInstance().getTimeInMillis();        
        progressTime1 = startTime;
        progressTime2 = startTime;
        minTps = Long.MAX_VALUE;
        maxTps = 0;
        midTps = 0;

        long minRcvdTps = Long.MAX_VALUE;
        long maxRcvdTps = 0;
        long midRcvdTps = 0;
        
		for(int i=0;i<PRF_ITER_ASYNC_CNT;i++, tps++) {
			callRequest = 
				dummyClientObject.createCallRequest("TestOperation", null);			
			dummyClientObject.callAsync(dummyClientObject.getConnectionHandlerToSend(), callRequest, null);
			progressTime1 = Calendar.getInstance().getTimeInMillis();
			if(progressTime1 > progressTime2 + 1000) {
				// System.out.println("TPS: "+tps);
				progressTime2 = progressTime1;
				if(maxTps<tps)
					maxTps = tps;
				if(minTps>tps)
					minTps = tps;
				midTps+= tps;
				tps = 0;
				
				int rcvdTps = dummyClientObject.getResponseReceivedCnt();
				if(maxRcvdTps<rcvdTps)
					maxRcvdTps = rcvdTps;
				if(minRcvdTps>rcvdTps)
					minRcvdTps = rcvdTps;
				midRcvdTps+= rcvdTps;				
			}
		}
		
        endTime = Calendar.getInstance().getTimeInMillis();
        midTps = (long) (midTps / ((endTime-startTime)/1000.0));
        midRcvdTps = (long) (midRcvdTps / ((endTime-startTime)/1000.0));
        
        System.out.println("Elapsed time for async model: "+ ((endTime-startTime)/1000.0)+". Mid. Resp. Time: "+(endTime-startTime)/PRF_ITER_ASYNC_CNT+". Max TPS: "+maxTps+". Min TPS: "+minTps+". Mid TPS: "+midTps+". Max RcvdTPS: "+maxRcvdTps+". Min RcvdTPS: "+minRcvdTps+". Mid RcvdTPS: "+midRcvdTps);
        assertTrue(maxTps > ALLOWED_MAX_ASYNC_TPS_LWM );
        
		dummyServerObject.destroy();
		dummyClientObject.destroy();
        
	}

}
